package com.lam.common.components.easyexcel.converter;

import java.lang.reflect.Field;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import com.alibaba.excel.converters.Converter;
import com.alibaba.excel.converters.ReadConverterContext;
import com.alibaba.excel.converters.WriteConverterContext;
import com.alibaba.excel.enums.CellDataTypeEnum;
import com.alibaba.excel.metadata.data.WriteCellData;
import com.alibaba.excel.metadata.property.ExcelContentProperty;
import com.lam.common.components.dict.DictUtil;
import com.lam.common.components.dict.annotation.Dict;
import com.lam.common.components.dict.model.DictDesc;
import com.lam.common.utils.BeanUtil;
import com.lam.common.utils.CollectionUtil;
import com.lam.common.utils.JsonUtil;
import com.lam.common.utils.StringUtils;

public class DictConverter implements Converter<Object> {

	private Map<String, Map<String, String>> dictMap = null;

	@Override
	public Class<?> supportJavaTypeKey() {
		return Date.class;
	}

	@Override
	public CellDataTypeEnum supportExcelTypeKey() {
		return CellDataTypeEnum.STRING;
	}

	/**
	 * 读Excel的时候会调用
	 */
	@Override
	public String convertToJavaData(ReadConverterContext<?> context) {
		
		return convert(context.getReadCellData().getStringValue(), context.getContentProperty());
	}
	
	private String convert(Object value, ExcelContentProperty contentProperty) {
		
		String strValue = JsonUtil.toString(value, "");
		Field field = contentProperty.getField();
		Dict dict = BeanUtil.getFieldAnnotation(field, Dict.class, BeanUtil.METHOD_TYPE_GETTER);
		if(dict == null) {
			return strValue;
		}
		
		if(dictMap == null) {
			dictMap = new HashMap<>();
		}
		
		Map<String, String> dictData = dictMap.get(DictUtil.uniqueKey(dict));
		if(dictData == null) {
			dictData = DictUtil.getDictInfo(new DictDesc(field.getName(), dict));
			dictMap.put(DictUtil.uniqueKey(dict), dictData);
		}
		
		if(CollectionUtil.isEmpty(dictData)) {
			return strValue;
		}
		
		return dictData.getOrDefault(StringUtils.trim(strValue), strValue);
	}

	/**
	 * 写Excel的时候会调用
	 */
	@Override
	public WriteCellData<?> convertToExcelData(WriteConverterContext<Object> context) throws Exception {
        
		return new WriteCellData<>(convert(context.getValue(), context.getContentProperty()));
	}
}
